The first creatable I/O-centric type you will examine is the DirectoryInfo class. This class contains a set of members used for creating, moving, deleting, and enumerating over directories and subdirectories. In addition to the functionality provided by its base class (FileSystemInfo), DirectoryInfo offers the key members in Table 20-3.
Table 20-3. Key Members of the DirectoryInfo Type
Member | Meaning in Life |
---|---|
Create() CreateSubdirectory() | Create a directory (or set of subdirectories) when given a path name. |
Delete() | Deletes a directory and all its contents. |
GetDirectories() | Returns an array of DirectoryInfo objects that represent all subdirectories in the current directory. |
GetFiles() | Retrieves an array of FileInfo objects that represent a set of files in the given directory. |
MoveTo() | Moves a directory and its contents to a new path. |
Parent | Retrieves the parent directory of this directory. |
Root | Gets the root portion of a path. |
You begin working with the DirectoryInfo type by specifying a particular directory path as a constructor parameter. Use the "." notation if you want to obtain access to the current working directory (the directory of the executing application). Here are some examples:
// Bind to the current working directory. DirectoryInfo dir1 = new DirectoryInfo("."); // Bind to C:\Windows, // using a verbatim string. DirectoryInfo dir2 = new DirectoryInfo(@"C:\Windows");
In the second example, you make the assumption that the path passed into the constructor (C:\Windows) already exists on the physical machine. However, if you attempt to interact with a nonexistent directory, a System.IO.DirectoryNotFoundException is thrown. Thus, if you specify a directory that is not yet created, you need to call the Create() method before proceeding:
// Bind to a nonexistent directory, then create it. DirectoryInfo dir3 = new DirectoryInfo(@"C:\MyCode\Testing"); dir3.Create();
Once you create a DirectoryInfo object, you can investigate the underlying directory contents using any of the properties inherited from FileSystemInfo. To see this in action, create a new Console Application named DirectoryApp and update your C# file to import System.IO.
Update your Program class with a new static method that creates a new DirectoryInfo object mapped to C:\Windows (adjust your path if need be) that displays a number of interesting statistics:
class Program { static void Main(string[] args) { Console.WriteLine("***** Fun with Directory(Info) *****\n"); ShowWindowsDirectoryInfo(); Console.ReadLine(); } static void ShowWindowsDirectoryInfo() { // Dump directory information. DirectoryInfo dir = new DirectoryInfo(@"C:\Windows"); Console.WriteLine("***** Directory Info *****"); Console.WriteLine("FullName: {0}", dir.FullName); Console.WriteLine("Name: {0}", dir.Name); Console.WriteLine("Parent: {0}", dir.Parent); Console.WriteLine("Creation: {0}", dir.CreationTime); Console.WriteLine("Attributes: {0}", dir.Attributes); Console.WriteLine("Root: {0}", dir.Root); Console.WriteLine("**************************\n"); } }
While your output might differ, you should see something similar to the following:
***** Fun with Directory(Info) ***** ***** Directory Info ***** FullName: C:\Windows Name: Windows Parent: Creation: 7/13/2009 10:20:08 PM Attributes: Directory Root: C:\ **************************
In addition to obtaining basic details of an existing directory, you can extend the current example to use some methods of the DirectoryInfo type. First, you can leverage the GetFiles() method to obtain information about all *.jpg files located under the C:\Windows\Web\Wallpaper directory.
Note If your machine does not have a C:\Windows\Web\Wallpaper directory, retrofit this code to read files of a directory on your machine (e.g., to read all *.bmp files from the C:\Windows directory).
The GetFiles() method returns an array of FileInfo objects, each of which exposes details of a particular file (you will learn the full details of the FileInfo type later in this chapter). Assume that you have the following static method of the Program class, which you call from Main():
static void DisplayImageFiles() { DirectoryInfo dir = new DirectoryInfo(@"C:\Windows\Web\Wallpaper"); // Get all files with a *.jpg extension. FileInfo[] imageFiles = dir.GetFiles("*.jpg", SearchOption.AllDirectories); // How many were found? Console.WriteLine("Found {0} *.jpg files\n", imageFiles.Length); // Now print out info for each file. foreach (FileInfo f in imageFiles) { Console.WriteLine("***************************"); Console.WriteLine("File name: {0}", f.Name); Console.WriteLine("File size: {0}", f.Length); Console.WriteLine("Creation: {0}", f.CreationTime); Console.WriteLine("Attributes: {0}", f.Attributes); Console.WriteLine("***************************\n"); } }
Notice you specify a search option when you call GetFiles(); you do this to look within all subdirectories of the root. Once you run the application, you see a listing of all files that match the search pattern.
You can programmatically extend a directory structure using the DirectoryInfo.CreateSubdirectory() method. This method can create a single subdirectory, as well as multiple nested subdirectories, in a single function call. This method illustrates how to do so, extending the directory structure of the C: drive with some custom subdirectories:
static void ModifyAppDirectory() { DirectoryInfo dir = new DirectoryInfo(@"C:\"); // Create \MyFolder off application directory. dir.CreateSubdirectory("MyFolder"); // Create \MyFolder2\Data off application directory. dir.CreateSubdirectory(@"MyFolder2\Data"); }
If you call this method from within Main() and examine your Windows directory using Windows Explorer, you will see that the new subdirectories are present and accounted for (see Figure 20-2).
Figure 20-2 Creating subdirectories
You are not required to capture the return value of the CreateSubdirectory() method, but you should be aware that a DirectoryInfo object representing the newly created item is passed back on successful execution. Consider the following update to the previous method:
static void ModifyAppDirectory() { DirectoryInfo dir = new DirectoryInfo("."); // Create \MyFolder off initial directory. dir.CreateSubdirectory("MyFolder"); // Capture returned DirectoryInfo object. DirectoryInfo myDataFolder = dir.CreateSubdirectory(@"MyFolder2\Data"); // Prints path to ..\MyFolder2\Data. Console.WriteLine("New Folder is: {0}", myDataFolder); }